import { Inject, Provide, Scope, ScopeEnum } from '@midwayjs/core';
import { UserEntity } from '../entity/user.entity';
import { Like, Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { encryptWithSalt, makeSalt } from '../utils';
import { JwtService } from '@midwayjs/jwt';
import { updateDTO } from '../dto/user';
import { PagingInfo } from '../dto/images';

@Provide()
@Scope(ScopeEnum.Request, { allowDowngrade: true })
export class UserService {
  @InjectEntityModel(UserEntity)
  userModel: Repository<UserEntity>;

  @Inject()
  jwtService: JwtService;

  //添加用户
  async addUser(u: UserEntity) {
    try {
      // 检查是否已经存在相同的记录
      const existingUser = await this.userModel.findOneBy({ email: u.email });
      if (existingUser) {
        return { success: false, message: '该邮箱已使用', data: u.email };
      }
      // 插入数据
      u.salt = makeSalt();
      u.password = encryptWithSalt(u.password, u.salt);
      const { identifiers } = await this.userModel.insert(u);
      return identifiers.length > 0;
    } catch (error) {
      // 捕获并记录错误
      console.error(`添加状态失败"${u.name}":`, error);
      throw new Error(`添加状态失败 "${u.name}": ${error.message}`);
    }
  }

  //用户登录
  async login(email: string, password: string) {
    const existingUser = await this.userModel.findOne({
      where: { email: email },
      relations: ['status'], // 加载关联的 StatusEntity
    });
    if (!existingUser) {
      return { success: false, message: '账户不存在', data: email };
    }
    const encryptedPassword = encryptWithSalt(password, existingUser.salt);
    if (encryptedPassword !== existingUser.password) {
      return { success: false, message: '账户或密码错误' };
    }
    const token = await this.jwtService.sign({ id: existingUser.id, status: existingUser.status });
    existingUser.password = undefined;
    existingUser.salt = undefined;
    return { token, user: existingUser };
  }

  //修改用户
  async updateUser(user: updateDTO) {
    let salt = undefined;
    if (user.password) {
      salt = makeSalt();
      user.password = encryptWithSalt(user.password, salt);
    }
    const data = await this.userModel.update({ id: user.id }, { ...user, salt });
    if (data.affected >= 1) {
      return data.affected;
    } else {
      return { success: false, message: '更新失败' };
    }
  }

  //获取用户列表
  async getUserList(pagingInfo: PagingInfo, user?: Partial<updateDTO>) {
    const where: any = { ...user };
    if (user?.name) where.name = Like(`%${user.name}%`);
    if (user?.email) where.email = Like(`%${user.email}%`);
    const [results, total] = await this.userModel.findAndCount({
      where: where,
      order: { id: 'ASC' },
      relations: ['status'],
      select: {
        id: true,
        name: true,
        email: true,
        createdAt: true,
      },
      skip: pagingInfo.skip * pagingInfo.take,
      take: pagingInfo.take,
    });
    const totalPages = Math.ceil(total / pagingInfo?.take);
    const remainingPages = totalPages - (pagingInfo.skip + 1);
    return {
      results,
      total,
      totalPages,
      remainingPages,
    };
  }

  //删除用户
  async delete(id: number) {
    return this.userModel.delete(id);
  }
}
